﻿#include "Array2D.h"
#include <iostream>
using namespace std;

Array2D::Array2D(int r, int c)
{
    rows = r;
    cols = c;
    data = new int* [rows];//为行分配内存空间
    for (int i = 0; i < rows; i++)
    {
        data[i] = new int[cols];//为列分配内存空间
        for (int j = 0; j < cols; j++)
        {
            data[i][j] = 0;//初始化
        }
    }
}

//重载[]运算符
InnerArray Array2D::operator[](int index)
{
    if (index < 0 || index >= rows)//判断下标是否越界
    {
        cout << "错误！";
        static int dummy = 0;
        return InnerArray(&dummy, 0);
    }
    return InnerArray(data[index], cols);
}

//重载()运算符
int& Array2D::operator()(int row, int col)
{
    if (row < 0 || row >= rows || col < 0 || col >= cols)
    {
        cout << "错误！";
        static int dummy = 0;
        return dummy;
    }
    return data[row][col];
}

Array2D::~Array2D()
{
    for (int i = 0; i < rows; i++) 
    {
        delete[] data[i];//释放列空间
    }
    delete[] data;//释放行空间
}

InnerArray::InnerArray(int* p, int c)
{
    cols = c;
    ptr = p;
}

int& InnerArray::operator[](int index)//重载[]运算符
{
    if (index < 0 || index >= cols)//判断下表是否越界
    {
        cout << "错误！";
        static int dummy = 0;
        return dummy;
    }
    return ptr[index];
}